package com.nettest.service.system;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nettest.dao.system.DeptDao;
import com.nettest.entity.BaseEntity;
import com.nettest.entity.system.Department;
import com.nettest.util.StringUtils;

@Service
@Transactional
public class DeptService {
	@Autowired
	private DeptDao deptDao;

	public BaseEntity save(BaseEntity entity) throws Exception {
		return deptDao.save((Department)entity);
	}

	public void delete(Long id) throws Exception {
		deptDao.delete(id);
	}

	public Department get(Serializable id) throws Exception {
		return deptDao.get(id);
	}
	
	public Department get(String deptId) throws Exception {
		List<Department> list = deptDao.findBySql("select r from Department r where r.deptId = ?",deptId);
		Department r = null;
		if(list != null && !list.isEmpty()) {
			r = list.get(0);
		}
		return r;
	}
	
	public List<Department> queryAllDept() {
		List<Department> list = deptDao.findBySql("select r from Department r ");
		return list;
	}

	public Department queryDeptById(String roleId) throws Exception {
		return get(roleId);
	}

	public void insertDept(Department dept) {
		String parentId = dept.getParentId();
		if (parentId != null) {
			String newDeptId = null;
			String maxDeptId = queryMaxDeptId(parentId);
			if (StringUtils.isEmpty(maxDeptId)) {
				newDeptId = "0".equals(parentId) ? "001" : (parentId + "001");
			}
			else {
				newDeptId = "00" + String.valueOf(NumberUtils.toLong(maxDeptId) + 1);
			}
			dept.setDeptId(newDeptId);
			deptDao.save(dept);
		}
	}

	public String queryMaxDeptId(String parentId) {		
		return deptDao.queryMaxDeptId(parentId);
	}

	public void updateDept(Department dept) throws Exception {
		Department dept2 = queryDeptById(dept.getDeptId());
		if(dept2 == null) throw new Exception("Department name: " + dept.getDeptName() + " has been deleted");
		dept2.setDeptName(dept.getDeptName());
		dept2.setMemo(dept.getMemo());
		deptDao.save(dept2);
	}

	public void delDeptById(String deptId) throws Exception {
		deptDao.delDeptById(deptId);
	}
	public List<Department> getSubDepts(String id) {
		Set<Criterion> set = new HashSet<Criterion>();
		set.add(Restrictions.eq("parentId",id == null ? "0" : id));
						
		Set<Order> orderSet = new HashSet<Order>();
		orderSet.add(Order.asc("deptId"));
		
		List<Department> result = deptDao.query(set,orderSet);
		return result;
	}
}
